package handler

import (
	"temp/constant"
	"temp/model"

	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"gorm.io/gorm"

	"temp/errors"
	"temp/service"
)

type DeptHandler struct {
	service *service.DeptService
}

func (d *DeptHandler) Detail(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		errors.HandlerParamError(c)
		return
	}
	detail, err := d.service.Detail(c.Request.Context(), id)
	if err != nil {
		errors.HandlerError(c, err)
		return
	}
	constant.SuccessResult(c, detail)
	return
}

func (d *DeptHandler) Create(c *gin.Context) {
	var dept model.Department
	if err := c.ShouldBindJSON(&dept); err != nil {
		errors.HandlerParamError(c)
		return
	}
	if err := d.service.Create(c.Request.Context(), &dept); err != nil {
		errors.HandlerError(c, err)
		return
	}
	constant.SuccessResultMessage(c, "创建部门成功")
}
func (d *DeptHandler) Update(c *gin.Context) {
	var dept model.Department
	if err := c.ShouldBindJSON(&dept); err != nil {
		errors.HandlerParamError(c)
		return
	}
	if err := d.service.Update(c.Request.Context(), &dept); err != nil {
		errors.HandlerError(c, err)
		return
	}
	constant.SuccessResultMessage(c, "更新部门成功")
}

func NewDeptHandler(db *gorm.DB, cache *redis.Client) *DeptHandler {
	return &DeptHandler{
		service: service.NewDeptService(db, cache),
	}
}
